{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h1 align=\"center\">Segmentation: Region Growing</h1>\n",
    "\n",
    "In this notebook we use one of the simplest segmentation approaches, region growing. We illustrate \n",
    "the use of three variants of this family of algorithms. The common theme for all algorithms is that a voxel's neighbor is considered to be in the same class if its intensities are similar to the current voxel. The definition of similar is what varies:\n",
    "\n",
    "* <b>ConnectedThreshold</b>: The neighboring voxel's intensity is within explicitly specified thresholds.\n",
    "* <b>ConfidenceConnected</b>: The neighboring voxel's intensity is within the implicitly specified bounds $\\mu\\pm c\\sigma$, where $\\mu$ is the mean intensity of the seed points, $\\sigma$ their standard deviation and $c$ a user specified constant.\n",
    "* <b>VectorConfidenceConnected</b>: A generalization of the previous approach to vector valued images, for instance multi-spectral images or multi-parametric MRI. The neighboring voxel's intensity vector is within the implicitly specified bounds using the Mahalanobis distance $\\sqrt{(\\mathbf{x}-\\mathbf{\\mu})^T\\Sigma^{-1}(\\mathbf{x}-\\mathbf{\\mu})}<c$, where $\\mathbf{\\mu}$ is the mean of the vectors at the seed points, $\\Sigma$ is the covariance matrix and $c$ is a user specified constant.\n",
    "\n",
    "We will illustrate the usage of these three filters using a cranial MRI scan (T1 and T2) and attempt to segment one of the ventricles."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# To use interactive plots (mouse clicks, zooming, panning) we use the notebook back end. We want our graphs \n",
    "# to be embedded in the notebook, inline mode, this combination is defined by the magic \"%matplotlib notebook\".\n",
    "%matplotlib notebook\n",
    "\n",
    "import SimpleITK as sitk\n",
    "\n",
    "%run update_path_to_download_script\n",
    "from downloaddata import fetch_data as fdata\n",
    "import gui\n",
    "\n",
    "# Using an external viewer (ITK-SNAP or 3D Slicer) we identified a visually appealing window-level setting\n",
    "T1_WINDOW_LEVEL = (1050,500)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Read Data and Select Seed Point(s)\n",
    "\n",
    "We first load a T1 MRI brain scan and select our seed point(s). If you are unfamiliar with the anatomy you can use the preselected seed point specified below, just uncomment the line."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "img_T1 = sitk.ReadImage(fdata(\"nac-hncma-atlas2013-Slicer4Version/Data/A1_grayT1.nrrd\"))\n",
    "# Rescale the intensities and map them to [0,255], these are the default values for the output\n",
    "# We will use this image to display the results of segmentation\n",
    "img_T1_255 = sitk.Cast(sitk.IntensityWindowing(img_T1, \n",
    "                                               windowMinimum=T1_WINDOW_LEVEL[1]-T1_WINDOW_LEVEL[0]/2.0, \n",
    "                                               windowMaximum=T1_WINDOW_LEVEL[1]+T1_WINDOW_LEVEL[0]/2.0), \n",
    "                       sitk.sitkUInt8)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "point_acquisition_interface = gui.PointDataAquisition(img_T1, window_level=(1050,500))\n",
    "\n",
    "#preselected seed point in the left ventricle  \n",
    "point_acquisition_interface.set_point_indexes([(132,142,96)])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "initial_seed_point_indexes = point_acquisition_interface.get_point_indexes()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## ConnectedThreshold\n",
    "\n",
    "We start by using explicitly specified thresholds, you should modify these (lower/upper) to see the effects on the \n",
    "resulting segmentation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "seg_explicit_thresholds = sitk.ConnectedThreshold(img_T1, seedList=initial_seed_point_indexes, lower=100, upper=170)\n",
    "# Overlay the segmentation onto the T1 image\n",
    "gui.MultiImageDisplay(image_list = [sitk.LabelOverlay(img_T1_255, seg_explicit_thresholds)],                   \n",
    "                      title_list = ['connected threshold result'])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "## ConfidenceConnected\n",
    "\n",
    "This region growing algorithm allows the user to implicitly specify the threshold bounds based on the statistics estimated from the seed points, $\\mu\\pm c\\sigma$. This algorithm has some flexibility which you should familiarize yourself with:\n",
    "* The \"multiplier\" parameter is the constant $c$ from the formula above. \n",
    "* You can specify a region around each seed point \"initialNeighborhoodRadius\" from which the statistics are estimated, see what happens when you set it to zero.\n",
    "* The \"numberOfIterations\" allows you to rerun the algorithm. In the first run the bounds are defined by the seed voxels you specified, in the following iterations $\\mu$ and $\\sigma$ are estimated from the segmented points and the region growing is updated accordingly."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "seg_implicit_thresholds = sitk.ConfidenceConnected(img_T1, seedList=initial_seed_point_indexes,\n",
    "                                                   numberOfIterations=0,\n",
    "                                                   multiplier=2,\n",
    "                                                   initialNeighborhoodRadius=1,\n",
    "                                                   replaceValue=1)\n",
    "\n",
    "gui.MultiImageDisplay(image_list = [sitk.LabelOverlay(img_T1_255, seg_implicit_thresholds)],                   \n",
    "                      title_list = ['confidence connected result'])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## VectorConfidenceConnected\n",
    "\n",
    "We first load a T2 image from the same person and combine it with the T1 image to create a vector image. This region growing algorithm is similar to the previous one, ConfidenceConnected, and allows the user to implicitly specify the threshold bounds based on the statistics estimated from the seed points. The main difference is that in this case we are using the Mahalanobis and not the intensity difference."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "img_T2 = sitk.ReadImage(fdata(\"nac-hncma-atlas2013-Slicer4Version/Data/A1_grayT2.nrrd\"))\n",
    "img_multi = sitk.Compose(img_T1, img_T2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "seg_implicit_threshold_vector = sitk.VectorConfidenceConnected(img_multi, \n",
    "                                                               initial_seed_point_indexes, \n",
    "                                                               numberOfIterations=2, \n",
    "                                                               multiplier=4)\n",
    "\n",
    "gui.MultiImageDisplay(image_list = [sitk.LabelOverlay(img_T1_255, seg_implicit_threshold_vector)],                   \n",
    "                      title_list = ['vector confidence connected result'])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Clean up, Clean up...\n",
    "\n",
    "Use of low level segmentation algorithms such as region growing is often followed by a clean up step. In this step we fill holes and remove small connected components. Both of these operations are achieved by using binary morphological operations, opening (BinaryMorphologicalOpening) to remove small connected components and closing (BinaryMorphologicalClosing) to fill holes.\n",
    "\n",
    "SimpleITK supports several shapes for the structuring elements (kernels) including:\n",
    "* sitkAnnulus\n",
    "* sitkBall\n",
    "* sitkBox\n",
    "* sitkCross\n",
    "\n",
    "The size of the kernel can be specified as a scalar (same for all dimensions) or as a vector of values, size per dimension.\n",
    "\n",
    "The following code cell illustrates the results of such a clean up, using closing to remove holes in the original segmentation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "vectorRadius=(1,1,1)\n",
    "kernel=sitk.sitkBall\n",
    "seg_implicit_thresholds_clean = sitk.BinaryMorphologicalClosing(seg_implicit_thresholds, \n",
    "                                                                vectorRadius,\n",
    "                                                                kernel)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And now we compare the original segmentation to the segmentation after clean up (using the GUI you can zoom in on the region of interest for a closer look)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "gui.MultiImageDisplay(image_list = [sitk.LabelOverlay(img_T1_255, seg_implicit_thresholds), \n",
    "                                sitk.LabelOverlay(img_T1_255, seg_implicit_thresholds_clean)], \n",
    "                  shared_slider=True,\n",
    "                  title_list = ['before morphological closing', 'after morphological closing'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.4.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
